//------------------------------ 擂台赛 ------------------------------------------------------
/**
 * 玩法 1服务器推送消息 同时开始游戏 时间15s
 *      2自己答完即刻显示正确答案 同时推送给对方
 *      3对方答完即刻推送给自己 显示出对方答案  
 */
var app = getApp();
var config = require('../../../config.js');
var index = 0;
var timer; // 计时器
var currQuestion;
//圆形进度条 
var interval;
var varName;
var ctx = wx.createCanvasContext('canvasArcCir');
var socketTask;
Page({
  data: {
    questionList: [],
    time: 0,  //当前时长
    totalTime: 15,//总时长
    currentQuestionPos: 1,
    //服务器需要的数据集合
    answersData: [],
    rightCount: 0,
    ansError: false,
    totalScore: 0,
    otherScore: 0,
    score: 0,
    isShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    index = 0;
    this.setUserInfo();
    this.toConnetSocket();
    this.getQuestionList();
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    this.setData({
      isShow: true,
    });
  },

  /**
   * 一个页面只会调用一次，代表页面已经准备妥当，可以和视图层进行交互。
   */
  onReady: function () {
    this.drawDefaultArc();
  },

  //设置用户信息
  setUserInfo: function () {
    var that = this;
    this.setData({
      userFaceUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName,
    });
    try {
      var resObj = wx.getStorageSync(config.currRoomInfo)
      console.log("房间号= " + resObj.roomNumber);
      that.setData({
        roomNumber: resObj.roomNumber
      });
      if (resObj) {
        // Do something with return value
        if (resObj.masterOpenId == app.globalData.openid) {
          //我是房主 设置受邀者信息
          if (resObj.slaveUser) {
            that.setData({
              slaveUserFace: resObj.slaveUser.avatarUrl,
              slaveUserNickName: resObj.slaveUser.nickname
            });
          }

        } else {
          //如果是受邀者  设置房主信息
          console.log("房主头像地址==" + resObj.masterUser.avatarUrl);
          that.setData({
            slaveUserFace: resObj.masterUser.avatarUrl,
            slaveUserNickName: resObj.masterUser.nickname
          });
        }
      }
    } catch (e) {
      // Do something when catch error
    }

  },


  /**
   * 建立连接
   */
  toConnetSocket: function () {
    var that = this;

    //=============web socket 连接================================
    app.connectSocket();
    socketTask = app.globalData.mSocketTask;
    socketTask.onOpen(function (res) {
      console.log('WebSocket连接已打开！')
      app.globalData.socketOpen = true


    });

    socketTask.onError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    socketTask.onClose(function (res) {
      app.globalData.socketOpen = false
      console.log('WebSocket 已关闭！')
      if (that.data.isShow) {
        wx.navigateBack({
          delta: -1
        })
      }

    });
    socketTask.onMessage(function (res) {
      console.log('收到服务器内容：' + res.data)
      var response = JSON.parse(res.data);

      // 7 收到对方提交答案
      if (response.type == 7) {
        console.log("收到对方提交答案");
        if (response.success == 0) {
          var resObj = response.data;
          var otherScore = resObj.totalScore;
          that.setData({
            otherAnswer: true,
            otherScore: otherScore,
            otherAid: resObj.aid
          });
        }
      }

      // 8 服务器通知客户端开始下一题
      if (response.type == 8) {
        if (response.success == 0) {
          console.log("服务器通知客户端开始下一题");
          index++;
          var resObj = response.data;
          if (index < that.data.questionList.length) {
            // 开始下一题
            that.startNextQuestion();
          }

        }
      }

      // 9本轮答题完成
      if (response.type == 9) {
        if (response.success == 0) {
          var resObj = response.data;
          var masterTotalScore = resObj.masterTotalScore;
          var slaveTotalScore = resObj.slaveTotalScore;
          console.log('../battleResult/battleResult?masterTotalScore=' + masterTotalScore + "&slaveTotalScore=" + slaveTotalScore);
          //跳转到答题结束页面
          setTimeout(function () {
            that.toResult(masterTotalScore, slaveTotalScore);
          }, 1000);


        }
      }

      // ==========退出 进行中的游戏 =============
      if (response.type == 11) {
        if (response.success == 0) {
          //type = 2  加入房间 成功
          var resObj = response.data;
          if (resObj.masterOpenId == app.globalData.openid) {
            //房主退出 直接退出房间
            wx.showModal({
              title: '提示',
              content: response.msg+"",
              success: function (res) {
                //返回上一页
                wx.navigateBack({
                  delta: -1
                })
              }
            })


          } else {
            //受邀者退出 继续等待  
            wx.showModal({
              title: '提示',
              content: response.msg+"",
              success: function (res) {
                //返回上一页
                wx.navigateBack({
                  delta: -1
                })
              }
            })

          }
        }

      }



    });

  },

  toResult: function (masterTotalScore, slaveTotalScore) {
    wx.redirectTo({
      url: '../../games/battleResult/battleResult?masterTotalScore=' + masterTotalScore + '&slaveTotalScore=' + slaveTotalScore,
    })
  },
  //获取本轮问题集合 在缓存中获取
  getQuestionList: function () {
    var that = this;
    try {
      var list = wx.getStorageSync(config.questionList)
      if (list) {
        that.setData({
          questionList: list
        });
        that.getNextQuestion();
        //延迟1s给用户反应
        setTimeout(function () {
          //开启动画和定时器
          that.startProgressAnim();
          that.startTimer();

        }, 2000);
      }
    } catch (e) {
      // Do something when catch error
    }

  },
  //获取下一个问题
  getNextQuestion: function () {

    currQuestion = this.data.questionList[index];
    var questionDesc = currQuestion.content;
    var answerList = currQuestion.answers;
    this.setData({
      currQuestion: currQuestion,
      questionDesc: questionDesc,
      answerList: answerList,
      isShowAnswer: false,
      otherAnswer: false,
      currentQuestionPos: index
    })


  },

  //选择答案点击事件
  selectedCase: function (event) {
    var that = this;
    if (that.data.isShowAnswer) {
      //如果已经显示答案，不能再次选择答案
      return;
    }
    //获取选择id
    var answerid = event.currentTarget.dataset.answerid;
    var correct = event.currentTarget.dataset.correct;


    var useTime = that.data.time;
    var score = (that.data.totalTime * 10) - (useTime * 10);

    //计算用户答对了几道题
    var count = that.data.rightCount + 1;
    if (correct == 1) {
      //如果答对了  
      var tempScore = that.data.totalScore + score;
      that.setData({
        rightCount: count,
        totalScore: tempScore,
        score: score
      });
    }else{
      that.setData({
        score: 0
      });
    }
    that.setData({
      isShowAnswer: true,
      answerid: answerid,
      isAnswerRight: correct == 1
    });

    //保存数据 等10道题全部结束 统一提交
    var answerObj = {};
    answerObj.qid = that.data.currQuestion.id;
    answerObj.aid = answerid;
    answerObj.correct = correct == 1 ? 0 : 1;
    answerObj.index = index;
    answerObj.score = that.data.score;
    answerObj.totalScore = that.data.totalScore;

    this.postAnserDataToServer(answerObj);

    that.pauseTimer();
    clearInterval(varName);


  },


  //开始下一题的答题
  startNextQuestion: function () {
    var that = this;
    //自动跳转到下一题
    setTimeout(function () {
      console.log("下一题开始了！！！！！");
      that.getNextQuestion();
      that.startTimer();
      that.startProgressAnim();
    }, 3000);

  },

  //时间到自动显示答案 用户没有点击行为 
  autoShowCase: function () {
    if (this.data.isShowAnswer) {
      //如果已经显示答案，不能再次选择答案
      return;
    }
    this.setData({
      isShowAnswer: true,
      answerid: -1,
      isAnswerRight: false
    })
    //设置缓存 并且向服务器提交答案
    //保存数据 等10道题全部结束 统一提交
    var answerObj = {};
    answerObj.qid = this.data.currQuestion.id;
    answerObj.correct = 1;
    answerObj.index = index;
    answerObj.score = 0;
    answerObj.totalScore = this.data.totalScore;

    this.postAnserDataToServer(answerObj);



  },

  // 开始倒计时
  startTimer: function () {
    this.setData({
      time: 0
    });
    this.countDownd();

  },

  // 自定义的暂停按钮  
  pauseTimer: function () {
    console.log("定时任务停止");
    if (timer) {
      clearTimeout(timer);
    }

  },

  // 倒计时
  countDownd: function () {
    var that = this;
    timer = setTimeout(function () {
      var currTime = that.data.time + 1;
      console.log("----Countdown----" + currTime);
      that.setData({
        time: currTime
      });

      if (currTime == that.data.totalTime) {
        //当时间到达20秒 结束计时
        that.pauseTimer();
        if (!that.data.isShowAnswer) {
          //自动显示答案
          that.autoShowCase();

        } else {
          console.log("currentIndex===" + index)
          // if (index != that.data.questionList.length) {
          //   // 开始下一题
          //   that.startNextQuestion();
          // }

        }
      } else {
        that.countDownd();
      }
    }, 1000);
  },

  /**
   *  //每次答题完成之后  立即向服务器提交答案
   */
  postAnserDataToServer: function (answerObj) {
    var that = this;
    if (app.globalData.socketOpen) {
      var msg = {
        openId: app.globalData.openid,
        roomNumber: that.data.roomNumber,
        type: 6,
        answer: answerObj
      }
      if (typeof (msg) === 'object') {
        msg = JSON.stringify(msg);
      }
      socketTask.send({
        data: msg,
        success: function (res) {
          console.log("向服务器提交答案成功" + msg);
        }
      });
    }

  },


  /**
   * 画默认的圆形
   */
  drawDefaultArc: function () {
    //创建并返回绘图上下文context对象。
    var cxt_arc = wx.createCanvasContext('canvasCircle');
    cxt_arc.setLineWidth(10);
    cxt_arc.setStrokeStyle('#e2e2e2');
    cxt_arc.setLineCap('round');
    cxt_arc.beginPath();

    cxt_arc.arc(40, 40, 30, 0, 2 * Math.PI, false);

    cxt_arc.stroke();
    cxt_arc.draw();
  },

  drawArc: function (s, e) {
    var x = 40, y = 40, radius = 30;
    ctx.setLineWidth(10);
    ctx.setStrokeStyle('#ff6600');

    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(x, y, radius, s, e, false);
    ctx.stroke()
    ctx.draw()
  },

  /**
   *开启度条
   */
  startProgressAnim: function () {
    clearInterval(varName);
    var that = this;
    var step = 1, startAngle = 0.5 * Math.PI, endAngle = 0;
    var animation_interval = 200, n = that.data.totalTime * 1000 / 200;
    var animation = function () {
      if (step <= n) {
        endAngle = step * 2 * Math.PI / n + 0.5 * Math.PI;
        that.drawArc(startAngle, endAngle);
        step++;
      } else {
        clearInterval(varName);
      }
    };
    varName = setInterval(animation, animation_interval);
  },

  /**
  * 返回首页
  */
  backTo: function (e) {
    wx.navigateBack({
      delta: -1
    });

  },

  /**
  * 邀请好友
  */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    wx: wx.request({
        url: config.getOneChance,
        data: {
          openId: app.globalData.openid
        },
        method: 'POST',
        success: function (res) {
            
        }
      })
    return {
      title: '一战到底',
      // path: "pages/games/throughGame/throughGame",
      path: '/pages/index/index?pageId=' + config.throughGame,
      
    }
  },

  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload: function () {
    //当页面卸载时 停止定时任务
    this.pauseTimer();
    //退出时 结束socket链接
    if (socketTask && app.globalData.socketOpen) {
      socketTask.close({
        success: function (res) {
          console.log("socket连接关闭成功");
        }

      });
    }

    this.setData({
      isShow: false,
    });

  },


})